<?php
/**
 * 个人中心
 */
namespace app\modules\cn\controllers;

use app\modules\app\models\QuestionCollect;
use app\modules\cn\models\MockPublic;
use yii;
use app\libs\IeltsController;
use app\libs\Method;
use app\modules\cn\models\User;
use app\modules\content\models\Education;
use app\modules\cn\models\RankingAll;
use app\modules\cn\models\RankingOrder;
use app\modules\cn\models\News;
use app\modules\exercise\models\IeltsTestSet;
use app\modules\cn\models\ExerciseListDetail;
use app\modules\content\models\Classes;

class UcenterController extends IeltsController  {

    public $enableCsrfValidation = false;
    public $layout = 'ucenter';

    function init (){
        parent::init();
        include_once($_SERVER['DOCUMENT_ROOT'].'/../libs/ucenter/ucenter.php');
    }

    /**
     * [actionIndex 个人中心]
     * @Author don
     * @Date   2021-09-26
     * @return [type]     [description]
     */
    public function actionIndex()
    {
        $uid = Yii::$app->session->get('uid');
        $user = User::find()->where(['uid'=>$uid])->asArray()->one();

        if ($user['address']) {
            $user['address'] = json_decode($user['address'], true);
        }

        $education = Education::getEducation();

        return $this->render('index', [
            'user' => $user,
            'education' => $education
        ]);
    }

    /**
     * [actionMember 会员积分]
     * @Author don
     * @Date   2021-09-26
     * @return [type]     [description]
     */
    public function actionMember()
    {
        $uid = Yii::$app->session->get('uid');
        // 积分分页
        $page = Yii::$app->request->get('page',1);
        $pageSize = 10;
        $limit = 'limit '.(($page - 1) * $pageSize).", $pageSize";
        $data = uc_user_integral1($uid, $limit, '');
        // @file_put_contents('log.txt', json_encode($data).PHP_EOL, FILE_APPEND );
        $data['total']= ceil($data['count'] / $pageSize);
        $data['page'] = $page;

        return $this->render('member', [
            'data' => $data
        ]);
    }

    /**
     * [actionPassword 密码安全]
     * @Author don
     * @Date   2021-09-26
     * @return [type]     [description]
     */
    public function actionPassword()
    {
        return $this->render('password');
    }

    /**
     * [actionMyOrder 我的订单]
     * @Author don
     * @Date   2021-09-26
     * @return [type]     [description]
     */
    public function actionOrder()
    {
        $uid = Yii::$app->session->get('uid');
        // $uid = 1653;
        $type = Yii::$app->request->get('type', 9);
        $page = Yii::$app->request->get('page', 1);
        $pageSize = 5;
        if (!$uid) {
            die('<script>alert("操作错误");history.go(-1);</script>');
        }

        $where = ' (uo.orderBelong=8 or uo.orderBelong=12) ';
        $data = json_decode(Method::post(Yii::$app->params['thinkuOrderUrl'] . "/pay/api/class", ['page' => 1, 'pageSize'=>999, 'uid' => $uid,'where'=>$where,'status'=>$type]), true);

        if (!empty($data['data'])) {
            foreach ($data['data'] as $key => $value) {
                if ($value['status'] == 1 && (time()-$value['createTime'] > 86400)) {
                    unset($data['data'][$key]);
                }
            }

            foreach ($data['data'] as $k => $v) {
                if ($v['orderBelong'] == 12) {
                    $courseTem = Classes::find()->asArray()->where('id='.$v['contentId'])->one();
                    $data['data'][$k]['course'] = $courseTem;
                } elseif ($v['orderBelong'] == 8) {
                    $data['data'][$k] = json_decode(Method::post(Yii::$app->params['ieltsUrl']."/order/api/class-detail",['id'=>$v['id']]),true);
                }
            }

            $data['count'] = count($data['data']);
        }
        $total = ceil($data['count'] / $pageSize);
        $offset = ($page-1)*$pageSize;
        $data['data'] = array_slice($data['data'], $offset, $pageSize);

        return $this->render('order', [
            'data' => $data,
            'page' => $page,
            'type' => $type,
            'total' => $total
        ]);
    }

    /**
     * [actionMyCourse 我的课程]
     * @Author don
     * @Date   2021-09-26
     * @return [type]     [description]
     */
    public function actionCourse()
    {
        $uid = Yii::$app->session->get('uid');
        // $uid = 1653;
        $type = Yii::$app->request->get('type', 1);
        $page = Yii::$app->request->get('page', 1);
        $pageSize = 5;
        if (!$uid) {
            die('<script>alert("操作错误");history.go(-1);</script>');
        }
        if ($type == 1) {
            $where = ' uo.order_form=1';
        } elseif ($type == 2) {
            $where = ' (uo.order_form is null or uo.order_form=2) ';
        } else {
            $where = '';
        }
        $where = $type ? $where.' and uo.orderBelong in (8,12) ':' uo.orderBelong in (8,12) ';

        $data = json_decode(Method::post(Yii::$app->params['thinkuOrderUrl'] . "/pay/api/class", ['page' => $page, 'pageSize'=>$pageSize, 'uid' => $uid,'where'=>$where]), true);
        // f_d($data);
        if (!empty($data['data'])) {
            foreach ($data['data'] as $key => $value) {
                if ($value['orderBelong'] == 12) {
                    $courseTem = Classes::find()->asArray()->where('id='.$value['contentId'])->one();
                    $data['data'][$key]['course'] = $courseTem;
                } elseif ($value['orderBelong'] == 8) {
                    $data['data'][$key] = json_decode(Method::post(Yii::$app->params['ieltsUrl']."/order/api/class-detail",['id'=>$value['id']]),true);
                }
            }
        }
        // f_d($data);
        $total = ceil($data['count'] / $pageSize);
        return $this->render('course', [
            'data' => $data,
            'page' => $page,
            'type' => $type,
            'total' => $total
        ]);
    }

    /**
     * [actionRecord 练习记录]
     * @Author don
     * @Date   2021-09-26
     * @return [type]     [description]
     */
    public function actionRecord()
    {
        // 晚上10.00-次日8.00，后台填的数据为0
        $night = strtotime(date('Y-m-d 22:00:00'));
        $morning = strtotime(date('Y-m-d 08:00:00', strtotime('+1 days')));
        if (time() > $night && time() < $morning) {
            $set_doing_num = $set_today_num = $set_heap_num = $set_already_num = 0;
        } else {
            $tmp1 = IeltsTestSet::findOne(1);
            $set_doing_num = $tmp1->num;
            $tmp2 = IeltsTestSet::findOne(2);
            $set_today_num = $tmp2->num;
            $tmp3 = IeltsTestSet::findOne(3);
            $set_heap_num = $tmp3->num;
            $tmp4 = IeltsTestSet::findOne(4);
            $set_already_num = $tmp4->num;
        }
        // 正在做题人数
        $doing_num = rand(8,20);
        // 今日做题人数
        $start_time = strtotime(date('Y-m-d').' 00:00:00');
        $end_time = strtotime(date('Y-m-d').' 23:59:59');
        $today_num = count(RankingAll::find()->select('userid')->where(['between', 'createtime', $start_time, $end_time])->distinct()->asArray()->all());
        // 累积做题人数
        $heap_num = count(RankingAll::find()->select('userid')->distinct()->asArray()->all());
        // 已助考雅思人数
        $already_num = 0;
        // 所有剑雅真题数
        $all_jianya_num = count(ExerciseListDetail::find()->all());
        // 用户做题数量
        $sql = "select userid,count(*) as num from `x2_ielts_test_result` group by userid";
        $all_user_do = Yii::$app->db->createCommand($sql)->queryAll();
        foreach ($all_user_do as $v) {
            if ($v['num'] >= $all_jianya_num) {
                $already_num++;
            }
        }

        $userId = Yii::$app->session->get('userId'); // 因老版雅思做题结果表用的是userId
        // 累计做题数量
        $exerciseNum = count(RankingAll::find()->where(['userid' =>$userId])->andWhere(['not', ['testid' => null]])->asArray()->All());
        // 累计做题天数
        $daycode = RankingAll::find()->where(['userid' =>$userId])->orderBy('createtime ASC')->asArray()->one();
        if (!empty($daycode)) {
            $timecode = time();
            $times =strtotime(date('Y-m-d',$daycode['createtime']));
            $code = $timecode - $times;
            $exerciseDays = ceil($code/3600/24);
        } else {
            $exerciseDays = 0;
        }
        // 今日做题数量
        $start_time = strtotime(date('Y-m-d 00:00:00',time()));
        $end_time = strtotime(date('Y-m-d 23:59:59',time()));
        $todayExerciseNum = count(RankingAll::find()->where(['between', 'createtime',$start_time, $end_time])->andWhere(['userid'=>$userId])->andWhere(['not', ['testid' => null]])->asArray()->All());

        // 烤鸭排行榜
        $ieltsRank = RankingOrder::find()->where(['typeid' =>0])->orderBy('order DESC')->andWhere(['not', ['userid' => null]])->distinct()->limit(4)->asArray()->All();
        foreach ($ieltsRank as $key => $value) {
            $name = User::find()->where(['id'=>$value['userid']])->asArray()->One();
            $ieltsRank[$key]['userName'] = $name['nickname'] ? $name['nickname'] : $name['userName'];
        }

        return $this->render('exercise', [
            'exerciseNum' => $exerciseNum,  // 个人累计做题数
            'exerciseDays' => $exerciseDays,  // 个人已累计学习天数
            'todayExerciseNum' => $todayExerciseNum,  // 个人今日做题数
            'ieltsRank' => $ieltsRank,  // 烤鸭排行榜
            'doing_num' => $doing_num + $set_doing_num,  // 正在做题人数
            'today_num' => $today_num + $set_today_num,  // 今日做题人数
            'heap_num' => $heap_num + $set_heap_num,  // 累计做题人数
            'already_num' => $already_num + $set_already_num,  // 已助考雅思人数
        ]);
    }

    /**
     * [actionMessage 我的消息]
     * @Author don
     * @Date   2021-09-26
     * @return [type]     [description]
     */
    public function actionMessage()
    {
        $uid = Yii::$app->session->get('uid');
        $page = Yii::$app->request->get('page', 1);
        $status = Yii::$app->request->get('status', 0);
        $pageSize = Yii::$app->request->get('pageSize', 10);

        // 查询用户的消息
        $noNews = News::getAllNews(1, $uid, $page, $pageSize); // 未读
        $isNews = News::getAllNews(2, $uid, $page, $pageSize); // 已读
        $allNews = News::getAllNews($status, $uid, $page, $pageSize); // 全部
        if ($status == 1) {
            News::updateAll(['status' => 2], "uid={$uid}");
        }
        return $this->render('message', [
            'noNews' => $noNews,
            'isNews' => $isNews,
            'allNews' => $allNews,
            'status' => $status
        ]);
    }

    /**
     * @Title  我的做题记录
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionMockRecord()
    {
        $page = Yii::$app->request->get('page', 1);
        $type = Yii::$app->request->get('type', 5);
        $uid = Yii::$app->session->get('uid');
        if ($uid == false) {
            header('Location:https://www.thinkuprep.com/login.html?source=10&url=http://www.thinkuprep.com/mock/record.html');
            exit;
        }
        MockPublic::MockStatus();
        $data = MockPublic::getRecord($type, $page);
        return $this->render('record', ['data' => $data]);
    }

    /**
     * @Title  我的收藏
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionCollectList()
    {
        $page = Yii::$app->request->get('page', 1);
        $typeid = Yii::$app->request->get('typeid');
        $startTime = Yii::$app->request->get('startTime');
        $endTime = Yii::$app->request->get('endTime');
        $uid = Yii::$app->session->get('uid');
        $where = 'uid=' . $uid;
        if ($uid == false) {
            header('Location:https://www.thinkuprep.com/login.html?source=10&url=http://www.thinkuprep.com/collect.html');
            exit;
        }
        if ($typeid != false) {
            $where .= ' and typeid=' . $typeid;
        }
        if ($startTime != false) {
            $where .= ' and uqc.createTime>' . strtotime($startTime);
        }
        if ($endTime != false) {
            $endTime = strtotime($endTime) + 86400;
            $where .= ' and uqc.createTime<' . $endTime;
        }
        $data = QuestionCollect::getCollectQuestion($where, $page);//获取所有的错题
        return $this->render('collect', ['data' => $data]);

    }

    /**
     * 学习课表
     * yoyo
     */
    public function actionTimetable(){
        $user = Yii::$app->session->get("userData");
        $uid = Yii::$app->session->get('uid');
//        $user['uid'] = 28091;
//        $user['phone'] = 18616033917;
        $id = json_decode(file_get_contents("https://api-crm.viplgw.cn/content/api/get-student-id-by-account?account={$user['uid']}&phone={$user['phone']}&email={$user['email']}"),true)['id'];
//        $id=62208;
        $content = $id != false ? json_decode(file_get_contents("https://course.viplgw.cn/cn/external-api/get-class?clientId=$id&belong=24"), true) : '';
        $this->title = '我的课表-【申友IELTS官网】';
        return $this->render('timetable',['content' => $content]);
    }
}
